package com.cgwx.tcservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cgwx.tcservice.entity.tc.TcCommandConfig;
import com.cgwx.tcservice.entity.vo.TcCommandExcelVo;
import com.cgwx.tcservice.service.TcCommandConfigService;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author GaoWei
 * @Date 2023/8/8 - 16:25
 */

@Api(tags = "EasyExcel遥控表格读取监听器")
public class TcCommandExcelListener extends AnalysisEventListener<TcCommandExcelVo> {
//    不可以交给Spring进行管理，需要自己new，不能注入其他对象
    public TcCommandConfigService tcCommandConfigService;
    private String tcFrameIdentifiers;

//    key为sheet编号，value为sheet对应的遥控指令代号
    Map<String,String> sheetNoToTcCommandCode = new HashMap<>();

//    构造函数
    public TcCommandExcelListener() {
    }

    public TcCommandExcelListener(
            TcCommandConfigService tcCommandConfigService,
            String tcFrameIdentifiers) {
        this.tcCommandConfigService = tcCommandConfigService;
        this.tcFrameIdentifiers = tcFrameIdentifiers;
    }

//    读取Excel中的内容
    @Override
    public void invoke(TcCommandExcelVo tcCommandExcelVo, AnalysisContext analysisContext) {
//        读取每个Sheet的第二行，插入到TcCommandConfig表中
//        创建对象，用于数据库存储
        TcCommandConfig tcCommandConfig = new TcCommandConfig();
//        仅处理第二行数据，作为遥控指令内容
        if(analysisContext.getCurrentRowNum() == 1){
//            赋值遥控帧代号
            tcCommandConfig.setTcFrameIdentifiers(tcFrameIdentifiers);
//            赋值遥控指令内容
            BeanUtils.copyProperties(tcCommandExcelVo,tcCommandConfig);
//            存储
            tcCommandConfigService.save(tcCommandConfig);
//            将遥控指令代号存储在Map中，key为sheet编号
            sheetNoToTcCommandCode.put(analysisContext.readSheetHolder().getSheetNo().toString(),tcCommandConfig.getTcCommandCode());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public Map<String, String> getSheetNoToTcCommandCode() {
        return sheetNoToTcCommandCode;
    }

    public void setSheetNoToTcCommandCode(Map<String, String> sheetNoToTcCommandCode) {
        this.sheetNoToTcCommandCode = sheetNoToTcCommandCode;
    }
}
